package cn.edu.seu.herald.informationplatform.dao.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class Dao {
	private static Dao daoInstance=null;
	protected Dao(){
		
	}
	public static Dao getDao(){
		if(daoInstance==null){
			daoInstance=new Dao();
		}
		return daoInstance;
	}
	public Connection getConnectionLeague(){
		try
		{
			Context initCtx = new InitialContext();
			Context envCtx = (Context) initCtx.lookup("java:comp/env");

			// Look up our data source
			DataSource ds = (DataSource)
			  envCtx.lookup("jdbc/league");

			// Allocate and use a connection from the pool
			Connection conn = ds.getConnection();
			return conn;
		}
		catch(Exception se)
		{
			se.printStackTrace();
			return null;
		}
	}
	public Connection getConnectionVoteTableBase(){
		try
		{
			InitialContext ctx = new InitialContext();
			DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/votetablebase");
			Connection conn = ds.getConnection();
			return conn;
		}
		catch(Exception se)
		{
			se.printStackTrace();
			return null;
		}
	}
	public void closeCon(Connection con){
		try {
			if(con!=null){
			con.close();}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public String getTrueName(String userName){
		Connection con=getConnectionLeague();
		try{
			PreparedStatement ps=con.prepareStatement("select truename from lg_user where username=?");
		    ps.setString(1,userName);
		    ResultSet rs=ps.executeQuery();
		    String resultString=new String();
		    while (rs.next()){
			   resultString=rs.getString(1);
			}
			return resultString;
		}catch (Exception e) {
			e.printStackTrace();
			return "False";
		}
		finally{
			closeCon(con);
		}
	}
	
}
